//
//  JSBridgeNavigation.swift
//  ToBeBigFE
//
//  Created by mingo on 2020/2/18.
//  Copyright © 2020 com.example. All rights reserved.
//

import Foundation

class JSBridgeNavigation : BridgeModuelBase {

    weak var viewController: WebViewController?

    init(viewController: WebViewController) {
        self.viewController = viewController
    }

    override func callFunc(_ funcName: String, callbackId: String, arg: [String : Any?]) {
        switch funcName {
        case "open": open(callbackId: callbackId, arg: arg)
        case "close": close(callbackId: callbackId, arg: arg)
        case "push": push(callbackId: callbackId, arg: arg)
        case "getParams": getParams(callbackId: callbackId, arg: arg)
        default: break
        }
    }
    
    private func open(callbackId: String, arg: [String : Any?]) {
        guard let vc = self.viewController else { return }
        guard let url = parseWebUrl(arg) else { return }
        let newVC = WebViewController()
        newVC.url = url
        newVC.project = arg["id"] as? String
        if let params = arg["params"] as? [String:Any?] {
            newVC.params = params
        }
        vc.present(newVC, animated: true, completion: nil)
    }

    private func close(callbackId: String, arg: [String : Any?]) {
        guard let vc = self.viewController else { return }
        if vc.navigationController != nil && vc.navigationController!.viewControllers.count > 1 {
            vc.navigationController?.popViewController(animated: true)
        } else if vc.isBeingPresented || vc.presentingViewController != nil {
            vc.dismiss(animated: true, completion: nil)
        }
    }
    
    private func push(callbackId: String, arg: [String : Any?]) {
        guard let vc = self.viewController else { return }
        guard let navVC = vc.navigationController else { return }
        guard let url = parseWebUrl(arg) else { return }
        let newVC = WebViewController()
        newVC.url = url
        newVC.project = arg["id"] as? String
        if let params = arg["params"] as? [String:Any?] {
            newVC.params = params
        }
        navVC.pushViewController(newVC, animated: true)
    }
    
    private func getParams(callbackId: String, arg: [String: Any?]) {
        guard let vc = self.viewController else { return }
        callback(callbackId: callbackId, json: vc.params)
    }
    
    private func parseWebUrl(_ arg: [String: Any?]) -> String? {
        if let id = arg["id"] as? String, let page = arg["page"] as? String {
            return WebManager.shared.getWebUrl(id: id, page: page)
        }
        else if let url = arg["url"] as? String {
            return url
        } else {
            return nil
        }
    }
}
